import React from 'react';
import { connect } from 'dva';
import { Redirect } from 'umi';
// import { stringify } from 'querystring';
import PageLoading from '@/components/PageLoading';

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };

  componentDidMount () {
    this.setState({
      isReady: true,
    });
    const { location, path, dispatch } = this.props;

    if (dispatch) {
      // 加载菜单
      dispatch({
        type: 'menu/loadMenuData',
        payload: { location },
      });

      // 加载配置
      dispatch({
        type: 'setting/getSetting',
        payload: { path },
      });

      // 加载jwtuser信息
      dispatch({
        type: 'menu/loadLoinInfo',
      });
    }
  }

  render () {
    const { isReady } = this.state;
    // You can replace it to your authentication rule (such as check token exists)
    const { children, loading, currentUser, loginStatus } = this.props;
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）

    // const isLogin = currentUser && currentUser.userid;
    const isLogin = loginStatus || currentUser
    // const queryString = stringify({
    //   redirect: window.location.href,
    // });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }

    if (!isLogin) {
      return <Redirect to={{
        pathname: '/login',
        // search: queryString,
      }}></Redirect>;
    }

    return children;
  }
}

export default connect(({ user, loading, login }) => ({
  loginStatus: login.status,
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout);
